from PIL import Image
import numpy as np
#import matplotlib.image as mpimg
import os, time

def 除背景(文件,閾=254,彩=False):
	m = 'RGBA' if 彩 else 'LA'
	圖片 = Image.open(文件).convert(m)
	點陣 = np.array(圖片)# asarray 不可寫
	if 彩:
		r,g,b,a = np.moveaxis(點陣, -1,0)
		透處 = (r>閾) & (g>閾) & (b>閾)
	else:
		灰階, 透明 = np.moveaxis(點陣, 2,0)
		透處 = 灰階>閾
	點陣[透處,-1] = 0
	圖片 = Image.fromarray(點陣,mode=m)
	return 圖片
def DFS_file_search(dict_name='./', out='裁'):
	# list.pop() list.append()這兩个方法就可以實現棧維护功能
	stack = []
	result_txt = []
	stack.append(dict_name)
	while len(stack) != 0:  # 棧空代表所有目錄均已完成訪問
		temp_name = stack.pop()
		try:
			temp_name2 = os.listdir(temp_name) # list [\"\",\"\",...]
			for eve in temp_name2:
				stack.append(temp_name + "/" + eve)  # 維持絕對路徑的表达
		except NotADirectoryError:
			result_txt.append(temp_name)
	res = []
	for eve_path in result_txt:
		if eve_path.find('.') != -1 and eve_path.find(out) == -1:
			if eve_path.split('.')[-1] in ('png', 'PNG', 'jpg', 'JPG', 'eps', 'EPS'):
				res.append(eve_path)
	return res

if __name__ == '__main__':
	read_root_path = 'trabajos'
	save_root_path = '透明'
	if not os.path.exists(save_root_path):
		os.mkdir(save_root_path)
	paths = DFS_file_search(read_root_path, save_root_path)
	if len(paths)>20:
		print(f'『{read_root_path}』中共有 {len(paths)} 幅圖片')
	else:
		print('欲處理之圖片之路徑：', paths)
	t1 = time.time()
	for path in paths:
		圖片 = 除背景(path,150,True)
		temp_name = path.split('.')[-2].split('/')[-1]
		圖片.save('./' + save_root_path + '/' + temp_name+'.png', 'png')
		#mpimg.imsave('./' + save_root_path + "/" + temp_name + '.png', 點陣, format='png')
		#print('裁畢 ' + path, '  耗時：', time.time()-t1, " 秒", ' 處理前尺寸:', ini_size, ' 處理後尺寸:',final_size)
	print('剾畢 ' + path, '  耗時：', time.time()-t1)